package com.filldream.fastboot.common.util;

import lombok.extern.slf4j.Slf4j;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.Jscode2sessionResult;
import weixin.popular.bean.user.User;

@Slf4j
public class MpUtil {

    public static class MpUserCredential {
        public String openId;
        public String unionId;
        public String sessionKey;

        public MpUserCredential(String openId, String unionId, String sessionKey) {
            this.openId = openId;
            this.unionId = unionId;
            this.sessionKey = sessionKey;
        }
    }

    public static MpUserCredential getUserCredential(String code,String appId,String secret) {
        Jscode2sessionResult jscode2sessionResult = SnsAPI.jscode2session(appId, secret, code);

        String openid = jscode2sessionResult.getOpenid();
        String unionId = jscode2sessionResult.getUnionid();
        String sessionKey = jscode2sessionResult.getSession_key();
        return new MpUserCredential(openid, unionId, sessionKey);
    }

    /**
     * 根据appid和key获取token
     *
     * @return
     */
//    public static String getMPAccessToken(String appId,String secret) {
//        log.debug("getMPAccessToken start");
//        Token token = TokenAPI.token(appId, secret);
//        log.debug("getMPAccessToken token=" + JsonUtil.toJson(token));
//        return token.getAccess_token();
//    }

    /**
     * 获取用户基本信息
     *
     * @param accessToken
     * @param openid
     * @return
     */
    public static User getUserInfo(String accessToken, String openid) {
        return SnsAPI.userinfo(accessToken, openid, "zh_CN");
    }
}